package com.rado.tf.gui.view.application.impl;

import com.rado.tf.gui.event.UIEvent;
import com.rado.tf.gui.event.UIEventTypes;
import com.rado.tf.gui.navigation.NavigationPlugin;
import com.rado.tf.gui.view.application.IApplicationPresenter;
import com.rado.tf.gui.view.application.IApplicationView;
import com.rado.tf.gui.view.menu.IMenuPresenter;
import com.vaadin.server.ClientConnector;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Created by parado on 17.03.14.
 */
@Component(ApplicationPresenterImpl.BEAN_NAME)
public class ApplicationPresenterImpl implements IApplicationPresenter
{
   public static final String BEAN_NAME = "applicationPresenter";

   @Resource
   private IApplicationView applicationView;

   @Resource
   private NavigationPlugin navigationPlugin;

   @Resource
   private ApplicationEventPublisher applicationEventPublisher;

   @Override
   @PostConstruct
   public void bind()
   {
      applicationView.addAttachListener(new ClientConnector.AttachListener()
      {
         @Override
         public void attach(ClientConnector.AttachEvent event)
         {
            applicationEventPublisher
                    .publishEvent(new UIEvent(ApplicationPresenterImpl.this, UIEventTypes.APPLICATION_VIEW_ATTACHED));
         }
      });
   }

   @Override
   public void onApplicationEvent(ApplicationEvent event)
   {
      if (event instanceof UIEvent)
      {
         if (event.getSource() instanceof IMenuPresenter)
         {
            navigationPlugin.handleMenuSelection(((UIEvent) event).getEventType());
         }
      }
   }

   @Override
   public IApplicationView getViewDisplay()
   {
      return applicationView;
   }
}
